import React, { useSyncExternalStore } from "react";

const createStore = () => {
  let store = { count: 0 };
  let listeners: (() => void)[] = [];

  const getState = () => store;

  const subscribe = (listener: () => void) => {
    listeners.push(listener);
    return () => {
      listeners = listeners.filter((l) => l !== listener);
    }
  };
  const dispatch = (action: { type: "increment" | "decrement" }) => {
    switch (action.type) {
      case "increment":
        store = { ...store, count: store.count + 1 };
        break;
      case "decrement":
        store = { ...store, count: store.count - 1 };
        break;
    }
    listeners.forEach((l) => l());
  }

  return {
    getState,
    subscribe,
    dispatch,
  };
};

const store = createStore();

// type useSyncExternalStoreType = <S>(subscribe: (setState: () => void) => void, getState: () => S) => S;

// const useSyncExternalStore: useSyncExternalStoreType = (subscribe, getState) => {
//   const [state, setState] = useReducer(() => getState(), getState())

//   useLayoutEffect(() => {

//     return subscribe(setState);
//   }, [subscribe]);

//   return state;
// }

export const Demo = React.memo(() => {
  const state = useSyncExternalStore(store.subscribe, store.getState);  

  return (
    <div>
      <h1>useSyncExternalStore</h1>
      <p>{state?.count}</p>
      <button onClick={() => store.dispatch({ type: "increment" })}>+1</button>
      <button onClick={() => store.dispatch({ type: "decrement" })}>-1</button>
    </div>
  )
})